package org.example.maven.pojo.user;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;


import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class UserDetailsImpl implements UserDetails {

    private User user;
    private List<String> permissions; // 新增权限字段



    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 返回用户权限列表（根据你的权限设计实现）
        // 将数据库中的角色转换为Spring Security需要的格式
        // 从数据库查询用户的权限（例如 "user:read"）
        // 1. 添加角色（带 ROLE_ 前缀）
        authorities.add(new SimpleGrantedAuthority("ROLE_" + user.getRole()));


        permissions.forEach(p ->
                authorities.add(new SimpleGrantedAuthority(p))
        );
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}
